import { FastifyPluginAsync } from "fastify";
import { ObjectId } from "mongodb";

const updateRoomRoutes: FastifyPluginAsync = async (
  fastify,
  opts,
): Promise<void> => {
  // 获取MongoDB集合
  const db = fastify.mongo.db;
  // 获取集合的辅助函数
  const getCollection = () => {
    // @ts-ignore
    return db.collection("orders");
  };
  const dateNow = Date.now();
  // 添加一个新的批量更新路由
  fastify.put("/update-rooms", async function (request, reply) {
    const { ids, agreeByAuthor, declineByAuthor, deleteByAuthor } =
      request.body as {
        ids: string[];
        deleteByAuthor: string;
        agreeByAuthor: string;
        declineByAuthor: string;
      };

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      reply.code(400);
      return { success: false, error: "必须提供要更新的ID数组" };
    }

    if (!deleteByAuthor && !agreeByAuthor && !declineByAuthor) {
      reply.code(400);
      return { success: false, error: "至少需要提供一个更新字段" };
    }

    try {
      const collection = getCollection();

      // 将字符串ID转换为ObjectId数组
      const objectIds = ids.map((id) => new ObjectId(id));

      // 使用 $in 操作符一次更新多个文档
      const result = await collection.updateMany(
        { _id: { $in: objectIds } },
        {
          $set: {
            ...(deleteByAuthor
              ? { deleteByAuthor, isDeleted: true, deletedAt: dateNow }
              : {}),
            ...(agreeByAuthor
              ? { agreeByAuthor, status: "success", agreedAt: dateNow }
              : {}),
            ...(declineByAuthor
              ? { declineByAuthor, status: "declined", declinedAt: dateNow }
              : {}),
          },
        },
      );

      if (result.matchedCount === 0) {
        reply.code(404);
        return { success: false, error: "没有找到匹配的记录" };
      }

      return {
        success: true,
        data: {
          matchedCount: result.matchedCount,
          modifiedCount: result.modifiedCount,
          ids,
        },
        message: "批量更新成功",
      };
    } catch (err) {
      fastify.log.error(err);
      reply.code(400);
      return { success: false, error: "批量更新失败" };
    }
  });
};

export default updateRoomRoutes;
